package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.data.analytics.constant.EventDataConstants;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.bussiness.recharge.PlatformRewardBussiness;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.maidian.DefaultEventTraceAction;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Objects;
import java.util.SortedMap;

@WebServlet(urlPatterns = "/sendReward")
public class SendReward extends BaseJsonHttpServlet {

	private static Logger logger = LogManager.getLogger(SendReward.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("request sendReward");
		HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
		JSONObject paramObj = httpJsonWebParam.getParamObj();
		String orderNo;
		int goodsId;
		int count;
		String openId;
		long userId;
		String sign;
		int type;             //类型，0：默认线下活动发奖；1：公众号购买发货
		String price;
		String platformUserId;	//平台用户编号
		try{
			orderNo = paramObj.getString("orderID");
			goodsId = paramObj.getIntValue("giftID");
			count = paramObj.getIntValue("giftNum");
			openId = paramObj.getString("userID");
			userId = paramObj.getLong("roleID");
			type = paramObj.getIntValue("type");
			price = paramObj.getString("price");
			platformUserId = paramObj.getString("platformUserId");
			if(null == price){
				price = "";
			}
			sign = paramObj.getString("sign");
		} catch (Exception e) {
			logger.error("sendReward args error:" + e);
			sendResult(response, 0, "args error");
			return;
		}
		if(count <= 0){
			logger.error("sendReward count error,count:{}", count);
			sendResult(response, 0, "giftNum error");
			return;
		}
		try{
			SortedMap<String, String> paramMap = SignHelper.getParamMap(paramObj);
			if(!SignHelper.checkSign(paramMap, AppKeyMgr.getAndroidAppSecret(), sign)){
				if(ServerListMgr.isCnMergeServer(WebServer.getInstance().getServerId())){
					if(!SignHelper.checkSign(paramMap, ChannelConfig.APP_SECRET_CONFIG, sign)){
						logger.error("sendReward sign error");
						sendResult(response, 0, "sign error");
						return;
					}
				}else {
					logger.error("sendReward sign error");
					sendResult(response, 0, "sign error");
					return;
				}
			}
			if(PlatformRewardBussiness.checkPlatformRewardOrder(orderNo)){
				logger.error("sendReward orderNo already exist,orderNo:{}", orderNo);
				sendResult(response, 0, "orderNo already exist");
				return;
			}else {
				UserInfo userInfo = UserBussiness.getUserInfoByUserId(userId);
				if (null == userInfo) {
					logger.error("sendReward user no find,orderNo:{},userId{}", orderNo, userId);
					sendResult(response, 0, "role no find");
					return;
				}
				if (!Objects.equals(userInfo.getOpenId(), openId)) {
					logger.error("sendReward openId error,orderNo:{},openId:{}; platformOpenId:{}", orderNo, userInfo.getOpenId(), openId);
					if (!Objects.equals(userInfo.getPlatformUserId(), platformUserId)) {
						logger.error("sendReward platformUserId error,orderNo:{},local platformUserId:{}; platformOpenId:{}", orderNo, userInfo.getPlatformUserId(), platformUserId);
						sendResult(response, 0, "dirty userId");
						return;
					}
				}
				int ret = GameWebServiceInvoke.platformSendReward(userId, goodsId, count, type);
				if(0 == ret){
					PlatformRewardBussiness.addPlatformReward(orderNo, userId, goodsId, count, type, price);
					sendResult(response, 1, "success");

					if(type == 1){
						//公众号商城
						try {
							DefaultEventTraceAction traceAction = new DefaultEventTraceAction(EventDataConstants.Order.ORDER_FINISH, userInfo);
							//防止时间差
							traceAction.build("#time", DateHelper.getCurrentDateTimeString());
							traceAction.build(EventDataConstants.Order.ORDER_SDKID, orderNo);
							traceAction.build(EventDataConstants.Order.ORDER_FINISH_PAY_TYPE, "CNY");
							if(StringUtils.isNullOrEmpty(price)){
								traceAction.build(EventDataConstants.Order.ORDER_FINISH_PAY_AMOUNT, 0);
							}else {
								traceAction.build(EventDataConstants.Order.ORDER_FINISH_PAY_AMOUNT, new BigDecimal(price).multiply(BigDecimal.valueOf(100)).longValue());
							}
							traceAction.build("pay_reason_markid", 3);
							traceAction.trace();
						}catch (Exception e){
							logger.error("", e);
						}
					}

					return;
				}else if(GameErrorCode.E_GOODS_NO_EXIST == ret){
					logger.error("sendReward fail,goods no found,orderNo:{},openId:{},userId:{},goodsId:{},count:{}", orderNo, openId, userId, goodsId, count);
					sendResult(response, 0, "gift no exist");
					return;
				}else if(GameErrorCode.E_PLATFORM_GOODS_IS_LOCK == ret){
					logger.error("sendReward fail,goods is lock,orderNo:{},openId:{},userId:{},goodsId:{},count:{}", orderNo, openId, userId, goodsId, count);
					sendResult(response, 0, "gift is lock");
					return;
				}else {
					logger.error("sendReward fail,unknown error:{},orderNo:{},openId:{},userId:{},goodsId:{},count:{}", ret, orderNo, openId, userId, goodsId, count);
					sendResult(response, 0, "unknown error");
					return;
				}
			}
		} catch (Exception e) {
			logger.error("sendReward error:" + e);
			sendResult(response, 0, "other error");
		}
	}
}
